import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Inject, Injectable, InjectionToken } from "@angular/core";
import { map, Observer, Observable } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message'

export const AuthToken = new InjectionToken('auth-token');

/**
 * HttpClient拦截器
 */
@Injectable()
export class HttpClientInterceptor implements HttpInterceptor {

  constructor(private message: NzMessageService, @Inject(AuthToken) private env: any) { }

  /**
   * 拦截处理
   * @param req http请求对象 
   * @param next http请求处理
   * @returns 处理结果
   */
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 改写请求头
    let newRequest = req.clone({
      setHeaders: {
        Authorization: 'token dc\\LuJuan1'
      },
      url: !req.url.startsWith('/nwf/') ? (req.url + (req.url.indexOf('?') == -1 ? '?' : '&') + `AppID=${this.env.appId}&AppSecret=${this.env.appSecret}`) : req.url
    });

    let messageId = this.message.loading('正在查询中...', { nzDuration: 6000 }).messageId;

    return next.handle(newRequest)
      .pipe(
        map(event => {
          if (event instanceof HttpResponse && event.body.result) {
            this.message.remove(messageId);

            return event.clone({ body: event.body.result });
          } else if (event instanceof HttpResponse) {
            this.message.remove(messageId);

            return event;
          } else {
            return event;
          }
        })
      );
  }
}